package com.itmuch.box.core.security;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.itmuch.box.domain.member.entity.Member;
import com.itmuch.box.domain.member.entity.MemberLog;
import com.itmuch.box.service.member.MemberLogService;
import com.itmuch.box.util.IPUtil;
import com.itmuch.box.util.TimeUtil;

//可以在这里将用户登录信息存入数据库。
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginSuccessHandler.class);

    //    @Autowired
    //    private MemberService memberService;
    @Autowired
    private MemberLogService memberLogService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
        Member member = securityUser.getMember();

        String ipAddress = IPUtil.getIpAddress(request);

        MemberLog log = new MemberLog();
        log.setIp(ipAddress);
        log.setTime(TimeUtil.now());
        log.setMemberId(member.getId());
        this.memberLogService.insert(log);

        // this.memberService.update(member);

        LOGGER.info("用户{}登陆, 登陆ip = {}, 登陆时间 = {}", member.getEmail(), ipAddress, new Date());

        super.onAuthenticationSuccess(request, response, authentication);
    }

}